package com.polaris.live.ui.user.task

import android.os.Bundle
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.view.View
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.ColorUtils
import com.blankj.utilcode.util.StringUtils
import com.polaris.live.R
import com.polaris.live.adapter.TaskCenterAnchorAdapter
import com.polaris.live.adapter.TaskCenterTodayAdapter
import com.polaris.live.common.R.color
import com.polaris.live.common.ext.setOnScrollChangeListenerCompat
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.mvvm.base2.BaseVbFragment
import com.polaris.live.common.network.parseState
import com.polaris.live.common.util.NavigationBarUtils
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.common.util.ViewUtils
import com.polaris.live.databinding.FragmentTaskCenterBinding
import com.polaris.live.dialog.common.TipsDialog
import com.polaris.live.popup.PublicTipsPopup
import com.polaris.live.popup.TaskRewardPopup
import com.polaris.live.resp.back_resp.UserTaskListV2Resp
import com.polaris.live.translation.R.string
import com.polaris.live.utils.TaskPrizeAnimationProxy
import com.polaris.live.utils.route.RouterUtils
import com.polaris.live.viewmodel.TaskCenterViewModel

/**
 * TaskCenterFragment
 *
 * @author Created by 天晴 on 2024/10/28 13:54
 * @since 1.0.0
 **/
class TaskCenterFragment : BaseVbFragment<TaskCenterViewModel, FragmentTaskCenterBinding>() {

    private val mAdapter: TaskCenterTodayAdapter by lazy {
        TaskCenterTodayAdapter()
    }

    private val mAnchorAdapter: TaskCenterAnchorAdapter by lazy {
        TaskCenterAnchorAdapter()
    }

    private var mTopBackListener: ((scrollY: Int) -> Unit)? = null
    private var mBindGoogleBackListener: ((taskIds: List<Long>?, receiveUserReward: Boolean?) -> Unit)? = null
    private var mBindGoogleBackByActiveListener: ((activeValue: Long?, dailyTask: Boolean?) -> Unit)? = null

    private val mProxy by lazy {
        TaskPrizeAnimationProxy(mBinding.flTask, this)
    }
    private var mUserTaskListV2Resp: UserTaskListV2Resp? = null
    private var mCanAgencyClaimedCount = 0 //未领数量主播
    private var mCanUserClaimedCount = 0 //未领数量用户

    private var mShowAgencyTasks = true //显示主播任务

    override fun initView(savedInstanceState: Bundle?) {
        ViewUtils.setMargin(
            mBinding.oneClickClaimRl,
            0,
            0,
            0,
            NavigationBarUtils.getNavigationBarHeight(requireContext())
        )
        mBinding.recycler.apply {
            layoutManager = LinearLayoutManager(requireContext(), RecyclerView.VERTICAL, false)
            adapter = mAnchorAdapter
            itemAnimator = null

        }
        mBinding.recyclerDay.apply {
            layoutManager = LinearLayoutManager(requireContext(), RecyclerView.VERTICAL, false)
            adapter = mAdapter
            itemAnimator = null
        }

        setClickClaim()
        initListener()
        initObserver()
    }

    override fun initData() {
        super.initData()
        mViewModel.getTask()
    }

    private fun setClickClaim() {
        if (mShowAgencyTasks) {
            mBinding.oneClickClaimBtn.setBackgroundResource(R.drawable.shape_task_bg)
            mBinding.oneClickClaimBtn.setTextColor(ColorUtils.getColor(R.color.white))
        } else {
            mBinding.oneClickClaimBtn.setBackgroundResource(R.drawable.shape_task_bg_2)
            mBinding.oneClickClaimBtn.setTextColor(ColorUtils.getColor(color.color_202028))
        }
        setOneClaim()
    }

    private fun setOneClaim() {
        val str = if (mShowAgencyTasks) mCanAgencyClaimedCount else mCanUserClaimedCount
        mBinding.oneClickClaimTv.text = getColoredString(
            str.toString(),
            StringUtils.getString(string.not_been_claimed, str.toString())
        )
    }

    private fun getColoredString(memberPrice: String, baseString: String): SpannableString {
        val fullString = String.format(baseString, memberPrice)
        val spannableString = SpannableString(fullString)
        val startIndex = fullString.indexOf(memberPrice)
        val endIndex = startIndex + memberPrice.length
        val color = if (mShowAgencyTasks) {
            ContextCompat.getColor(requireContext(), R.color.color_893AFF)
        } else {
            ContextCompat.getColor(requireContext(), R.color.color_aaf000)
        }
        spannableString.setSpan(ForegroundColorSpan(color), startIndex, endIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        return spannableString
    }

    private fun initListener() {
        mAdapter.setItemListener({ explainType ->
            mUserTaskListV2Resp?.rewardExplains?.get(explainType.toString())?.let { explain ->
                TipsDialog.show(requireContext(), explain.title, explain.content)
            }
        }, { item ->
            when {
                item.rewards.any { it.status == 1L } -> { //可领取
                    val taskIds = item.rewards
                        .filter { it.status == 1L }
                        .map { it.taskId }
                    mViewModel.taskReceive(taskIds, true)
                }

                item.rewards.any { it.status == 0L } -> {  //进行中
                    item.rewards.firstOrNull { it.status == 0L }?.router?.let { router ->
                        RouterUtils.routerGoto(router)
                    }
                }
            }

        })
        mAnchorAdapter.setItemListener({ explainType ->
            mUserTaskListV2Resp?.rewardExplains?.get(explainType.toString())?.let { explain ->
                TipsDialog.show(requireContext(), explain.title, explain.content)
            }
        }, { item ->
            when {
                item.rewards.any { it.status == 1L } -> { //可领取
                    val taskIds = item.rewards
                        .filter { it.status == 1L }
                        .map { it.taskId }
                    mViewModel.taskReceive(taskIds)
                }

                item.rewards.any { it.status == 0L } -> {  //进行中
                    item.rewards.firstOrNull { it.status == 0L }?.router?.let { router ->
                        RouterUtils.routerGoto(router)
                    }
                }
            }

        })
        mBinding.nested.setOnScrollChangeListenerCompat { scrollY ->
            mTopBackListener?.invoke(scrollY)
        }
        mBinding.oneClickClaimBtn.setOnSingleClickListener {
            if (mShowAgencyTasks) {
                mViewModel.taskReceive(null)
            } else {
                mViewModel.taskReceive(null, true)
            }
        }
        mBinding.todayRl.setOnClickListener {
            mShowAgencyTasks = false
            mBinding.recycler.visibility = View.GONE
            mBinding.dayRecyclerLl.visibility = View.VISIBLE
            mBinding.taskTitleRightImg.setImageResource(R.drawable.task_today_title_half)
            mBinding.taskTitleLeftImg.setImageResource(R.drawable.task_no_selected_left)
            setClickClaim()

        }
        mBinding.anchorRl.setOnClickListener {
            mShowAgencyTasks = true
            mBinding.recycler.visibility = View.VISIBLE
            mBinding.dayRecyclerLl.visibility = View.GONE
            mBinding.taskTitleRightImg.setImageResource(R.drawable.task_no_selected_right)
            mBinding.taskTitleLeftImg.setImageResource(R.drawable.task_today_achor_half)
            setClickClaim()
        }
        mBinding.activeView.setOnClickListener({ dailyTask, activeValue ->
            mViewModel.taskActiveReceive(activeValue, dailyTask)
        }) { explainType ->
            mUserTaskListV2Resp?.rewardExplains?.get(explainType.toString())?.let { explain ->
                TipsDialog.show(requireContext(), explain.title, explain.content)
            }
        }
    }

    private fun initObserver() {
        mViewModel.taskLiveData.observe(this) { resultState ->
            parseState(resultState, {
                initDataView(it)
            }, {
                ToastGravity.showGravity(it.errorMsg)
            })
        }
        mViewModel.taskReceiveData.observe(this) { resultState ->
            parseState(resultState, {
                mViewModel.getTask()
                if (it.taskIds == null) {
                    mProxy.setData(it.data.rewards)
                } else {
                    if (it.data.rewards.size > 6) {
                        mProxy.setData(it.data.rewards)
                    } else if (it.data.rewards.isNotEmpty()) {
                        TaskRewardPopup.showPop(requireContext(), mViewModel, it.data)
                    }

                }
            }, {
                if (it.errCode == 980006001) { // 没有绑定谷歌验证
                    PublicTipsPopup.show(
                        requireContext(), this,
                        StringUtils.getString(string.prompt),
                        StringUtils.getString(string.bind_your_google_account),
                        StringUtils.getString(string.go_bind),
                        StringUtils.getString(string.cancel),
                        onTop = {
                            val taskIds = it.ext?.get("taskIds") as? List<Long>
                            val receiveUserReward = it.ext?.get("receiveUserReward") as? Boolean
                            mBindGoogleBackListener?.invoke(taskIds, receiveUserReward)
                        },
                        onBottom = {
                        }
                    )

                } else {
                    ToastGravity.showGravity(it.errorMsg)
                }

            })
        }
        mViewModel.taskActiveReceiveData.observe(this) { resultState ->
            parseState(resultState, {
                mViewModel.getTask()
                if (it.data.rewards.size > 6) {
                    mProxy.setData(it.data.rewards)
                } else if (it.data.rewards.isNotEmpty()) {
                    TaskRewardPopup.showPop(requireContext(), mViewModel, it.data)
                }
            }, {
                if (it.errCode == 980006001) { // 没有绑定谷歌验证
                    PublicTipsPopup.show(
                        requireContext(), this,
                        StringUtils.getString(string.prompt),
                        StringUtils.getString(string.bind_your_google_account),
                        StringUtils.getString(string.go_bind),
                        StringUtils.getString(string.cancel),
                        onTop = {
                            val activeValue = it.ext?.get("activeValue") as? Long
                            val dailyTask = it.ext?.get("dailyTask") as? Boolean
                            mBindGoogleBackByActiveListener?.invoke(activeValue, dailyTask)
                        },
                        onBottom = {
                        }
                    )

                } else {
                    ToastGravity.showGravity(it.errorMsg)
                }

            })
        }
    }

    private fun initDataView(data: UserTaskListV2Resp) {
        mUserTaskListV2Resp = data
        mBinding.loginView.setData(data.dailyTask)
        //没有个人每日任务
        if (data.dailyTask.tasks.isEmpty() && data.activeTask.tasks.isEmpty() && data.activeTask.weekTasks.isEmpty()) {
            mBinding.tasksUserRl.visibility = View.GONE
            if (data.agencyTasks.tasks.isEmpty()) { //没有工会任务
                mBinding.tasksNoUserRl.visibility = View.GONE
            } else {
                mBinding.tasksNoUserRl.visibility = View.VISIBLE
                mBinding.noUserBg.setBackgroundResource(R.drawable.task_title_2)
                mBinding.noUserTv.text = StringUtils.getString(string.anchor_task)
                if (mShowAgencyTasks) {
                    mShowAgencyTasks = true
                    mBinding.recycler.visibility = View.VISIBLE
                    mBinding.dayRecyclerLl.visibility = View.GONE
                }

                mAnchorAdapter.setList(data.agencyTasks.tasks)
            }
        } else {
            if (data.agencyTasks.tasks.isEmpty()) { //没有工会任务
                mBinding.tasksNoUserRl.visibility = View.VISIBLE
                mBinding.tasksUserRl.visibility = View.GONE
                mBinding.noUserBg.setImageResource(R.drawable.task_title_1)
                mBinding.noUserTv.text = StringUtils.getString(string.daily_tasks)
                mShowAgencyTasks = false

                mBinding.recycler.visibility = View.GONE
                mBinding.dayRecyclerLl.visibility = View.VISIBLE
            } else {
                mBinding.tasksUserRl.visibility = View.VISIBLE
                mBinding.tasksNoUserRl.visibility = View.GONE
                if (mShowAgencyTasks) {
                    mShowAgencyTasks = true
                    mBinding.recycler.visibility = View.VISIBLE
                    mBinding.dayRecyclerLl.visibility = View.GONE
                    mBinding.taskTitleRightImg.setImageResource(R.drawable.task_no_selected_right)
                    mBinding.taskTitleLeftImg.setImageResource(R.drawable.task_today_achor_half)
                } else {
                    mBinding.taskTitleRightImg.setImageResource(R.drawable.task_today_title_half)
                    mBinding.taskTitleLeftImg.setImageResource(R.drawable.task_no_selected_left)
                }
                mAnchorAdapter.setList(data.agencyTasks.tasks)
            }
            mBinding.activeView.setData(data.activeTask)
            mAdapter.setList(data.userTasks.tasks)
        }
        mCanAgencyClaimedCount = 0
        mCanUserClaimedCount = 0
        data.agencyTasks.tasks.forEach { task ->
            task.rewards.forEach { reward ->
                if (reward.status == 1L) {
                    mCanAgencyClaimedCount++
                }
            }
        }
        data.userTasks.tasks.forEach { task ->
            task.rewards.forEach { reward ->
                if (reward.status == 1L) {
                    mCanUserClaimedCount++
                }
            }
        }
        setClickClaim()
        mBinding.oneClickClaimRl.visibility = View.VISIBLE
    }

    fun setTopBack(topBack: (scrollY: Int) -> Unit) {
        this.mTopBackListener = topBack
    }

    fun setBindGoogleBack(bindGoogleBack: (taskIds: List<Long>?, receiveUserReward: Boolean?) -> Unit) {
        this.mBindGoogleBackListener = bindGoogleBack
    }

    /**
     * 领取活跃奖励
     */
    fun setBindGoogleBackByActive(bindGoogleBackByActive: (activeValue: Long?, dailyTask: Boolean?) -> Unit) {
        this.mBindGoogleBackByActiveListener = bindGoogleBackByActive
    }

    fun bindSuccess(taskIds: List<Long>?, receiveUserReward: Boolean?) {
        mViewModel.taskReceive(taskIds, receiveUserReward)
    }

    fun bindSuccess(activeValue: Long, dailyTask: Boolean) {
        mViewModel.taskActiveReceive(activeValue, dailyTask)
    }

}